var entity = { name:"", sex: 'true', age: 0, phone:"", qq:"" };
var page_query = { query: {}, sort: {}, total: 0, page: 1, size: 10};
var vm = new Vue({
	el: 'body',
	data: {
		hp: null,
		current: Object.assign({}, entity),
		
		query: Object.assign({}, page_query),
		isprev: false, isnext: false,
		sort_name:{},
		search_query:{}
	},
	methods: {
		getlist: function () {
			delete this.query.data;
			delete this.query.pages;
			this.query.size = parseInt(this.query.size);
			this.hp.invoke("base.user", "get_page_list", this.query, function (data) {
				if (data) {
					vm.query = new Proxy(data, {
						set(t, k, v, r){
							var p = Reflect.set(t, k, v, r);
							if (k == "page") {
								vm.getlist();
							}
							return p;
						}
					});
					vm.query.pages = parseInt(vm.query.total / vm.query.size + (vm.query.total % vm.query.size > 0 ? 1 : 0));
					vm.isprev = vm.query.page == 1;
					vm.isnext = vm.query.page == vm.query.pages;
				}
			});
		},
		save: function () {
			this.hp.invoke("base.user", "save", this.current, function (data) {
				if (data) layer.msg("保存成功");
				else layer.msg("保存失败");
				this.current = Object.assign({}, entity);
			});
		},
		empty: function (item) {
			this.current = Object.assign({}, entity);
		},
		toJson: function (obj) {
			return JSON.stringify(obj);
		},
		sort: function (name) {
			if (!this.sort_name[name]) this.sort_name[name] = 1;
			this.sort_name[name] = this.sort_name[name] == 1 ? -1 : 1;
			this.query.sort = {};
			this.query.sort[name] = this.sort_name[name];
			vm.getlist();
		},
		search: function (tj) {
			var search_query = [];
			let query = this.search_query;
			
			if (query.name) search_query.push({name: { $regex: query.name}});
			if (query.sex) search_query.push({sex: query.sex == "男" ? "true" : "false"});
			
			if (query.age && query.age1) {
				search_query.push({age: { $gte: parseInt(query.age), $lte: parseInt(query.age1)}});
			}else {
				if (query.age)  search_query.push({age: { $gte: parseInt(query.age)}});
				else if (query.age1)  search_query.push({age: { $lte: parseInt(query.age1) }});
			}
			if (query.qq) search_query.push({qq: { $regex: query.qq}});
			this.query.total = 0;
			this.query.page = 1;
			this.query.query = search_query.length > 0 ? { [tj]: search_query} : {};
			this.getlist();
		}
	},
	ready: function () {
		this.hp = cnynld_hprose.init();
		this.hp.register_push("user.save", function (data) {
			vm.getlist(); //  这里不用 this.getlist() 是因为闭包，此处回调中的this对象是window，，
		});
		this.getlist();
	}
});